<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">房间管理</h1>
      <p class="page-description">查看和管理所有房间信息</p>
    </div>
    
    <!-- 筛选器 -->
    <a-card class="filter-card" :bordered="false">
      <div class="filter-container">
        <a-form :model="filters" @submit="handleSearch" class="filter-form" :label-col-style="{ width: '80px', flexShrink: 0 }">
          <!-- 第一行 -->
          <div class="filter-row">
            <a-form-item label="房间号" class="filter-item">
              <a-input
                v-model="filters.search"
                placeholder="搜索房间号"
                allow-clear
                style="width: 180px"
              />
            </a-form-item>
            
            <a-form-item label="房间类型" class="filter-item">
              <a-select
                v-model="filters.type"
                placeholder="选择房间类型"
                allow-clear
                style="width: 180px"
              >
                <a-option
                  v-for="option in roomStore.roomTypeOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
            
            <a-form-item class="button-group">
              <a-space :size="8">
                <a-button type="primary" html-type="submit" :loading="roomStore.loading">
                  <template #icon>
                    <icon-search />
                  </template>
                  搜索
                </a-button>
                <a-button @click="handleReset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </div>
          
          <!-- 第二行 -->
          <div class="filter-row">
            <a-form-item label="状态" class="filter-item">
              <a-select
                v-model="filters.status"
                placeholder="选择状态"
                allow-clear
                style="width: 180px"
              >
                <a-option
                  v-for="option in roomStore.roomStatusOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </div>
        </a-form>
        
        <div class="action-buttons">
          <a-space :size="12">
            <a-button type="primary" @click="handleAddRoom">
              <template #icon>
                <icon-plus />
              </template>
              添加房间
            </a-button>
            <a-button @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出数据
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 房间列表 -->
    <a-card class="table-card" :bordered="false">
      <a-table
        :columns="columns"
        :data="roomStore.rooms"
        :loading="roomStore.loading"
        :pagination="paginationConfig"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #roomType="{ record }">
          {{ record.room_type?.name || '-' }}
        </template>
        
        <template #price="{ record }">
          ¥{{ record.room_type?.base_price || 0 }}/晚
        </template>
        
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.room_status?.id)">
            {{ record.room_status?.name || '-' }}
          </a-tag>
        </template>
        
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleViewRoom(record)">
              <template #icon>
                <icon-eye />
              </template>
              查看
            </a-button>
            <a-button type="text" size="small" @click="handleEditRoom(record)">
              <template #icon>
                <icon-edit />
              </template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个房间吗？"
              @ok="handleDeleteRoom(record.id)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!-- 房间表单模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :width="600"
      :ok-text="modalMode === 'view' ? '关闭' : '确定'"
      :hide-cancel="modalMode === 'view'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="房间号" field="room_number">
              <a-input 
                v-model="formData.room_number" 
                placeholder="请输入房间号"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="楼层" field="floor">
              <a-input-number
                v-model="formData.floor"
                placeholder="请输入楼层"
                :min="1"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="房间类型" field="room_type_id">
              <a-select
                v-model="formData.room_type_id"
                placeholder="请选择房间类型"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              >
                <a-option
                  v-for="option in roomStore.roomTypeOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="房间状态" field="room_status_id">
              <a-select
                v-model="formData.room_status_id"
                placeholder="请选择房间状态"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              >
                <a-option
                  v-for="option in roomStore.roomStatusOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="面积(m²)" field="area">
              <a-input-number
                v-model="formData.area"
                placeholder="请输入面积"
                :min="0"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最大入住人数" field="max_guests">
              <a-input-number
                v-model="formData.max_guests"
                placeholder="请输入最大入住人数"
                :min="1"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="床型" field="bed_type">
          <a-input 
            v-model="formData.bed_type" 
            placeholder="请输入床型"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
        
        <a-form-item label="房间描述" field="description">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入房间描述"
            :rows="3"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRoomStore } from '@/stores/room'
import {
  IconPlus,
  IconSearch,
  IconRefresh,
  IconEye,
  IconEdit,
  IconDelete,
  IconDownload
} from '@arco-design/web-vue/es/icon'

const roomStore = useRoomStore()

// 筛选条件
const filters = reactive({
  search: '',
  type: '',
  status: ''
})

// 模态框状态
const modalVisible = ref(false)
const modalTitle = ref('')
const modalMode = ref('add') // add | edit | view
const currentRoomId = ref(null)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  room_number: '',
  floor: 1,
  room_type_id: '',
  room_status_id: '',
  area: 0,
  max_guests: 1,
  bed_type: '',
  description: ''
})

// 表单验证规则
const formRules = {
  room_number: [
    { required: true, message: '请输入房间号' }
  ],
  floor: [
    { required: true, message: '请输入楼层' },
    { type: 'number', min: 1, message: '楼层必须大于0' }
  ],
  room_type_id: [
    { required: true, message: '请选择房间类型' }
  ],
  room_status_id: [
    { required: true, message: '请选择房间状态' }
  ],
  area: [
    { required: true, message: '请输入面积' },
    { type: 'number', min: 0, message: '面积必须大于等于0' }
  ],
  max_guests: [
    { required: true, message: '请输入最大入住人数' },
    { type: 'number', min: 1, message: '最大入住人数必须大于0' }
  ],
  bed_type: [
    { required: true, message: '请输入床型' }
  ]
}

// 表格列配置
const columns = [
  { title: '房间号', dataIndex: 'room_number', width: 100 },
  { title: '类型', slotName: 'roomType', width: 120 },
  { title: '价格', slotName: 'price', width: 120 },
  { title: '状态', slotName: 'status', width: 100 },
  { title: '面积', dataIndex: 'area', width: 80, render: ({ record }) => `${record.area}m²` },
  { title: '床型', dataIndex: 'bed_type', width: 120 },
  { title: '最大入住人数', dataIndex: 'max_guests', width: 120 },
  { title: '操作', slotName: 'actions', width: 180, fixed: 'right' }
]

// 分页配置
const paginationConfig = computed(() => ({
  current: roomStore.pagination.current,
  pageSize: roomStore.pagination.size,
  total: roomStore.pagination.total,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
}))

// 获取状态颜色
const getStatusColor = (statusId) => {
  const colors = {
    1: 'green',   // 可用
    2: 'red',     // 已入住
    3: 'blue',    // 已预订
    4: 'orange'   // 维护中
  }
  return colors[statusId] || 'gray'
}

// 处理搜索
const handleSearch = () => {
  roomStore.setFilters(filters)
  roomStore.fetchRooms()
}

// 处理重置
const handleReset = () => {
  roomStore.resetFilters()
  Object.assign(filters, {
    search: '',
    type: '',
    status: ''
  })
  roomStore.fetchRooms()
}

// 处理导出数据
const handleExport = () => {
  try {
    // 准备导出数据
    const exportData = roomStore.rooms.map(room => ({
      '房间号': room.room_number,
      '楼层': room.floor,
      '房间类型': room.room_type?.name || '-',
      '状态': room.room_status?.name || '-',
      '面积(m²)': room.area,
      '最大入住人数': room.max_guests,
      '床型': room.bed_type,
      '价格(元/晚)': room.room_type?.base_price || 0,
      '描述': room.description || '-'
    }))

    // 转换为CSV格式
    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => {
        const value = row[header]
        // 处理包含逗号或换行的字段
        if (typeof value === 'string' && (value.includes(',') || value.includes('\n'))) {
          return `"${value.replace(/"/g, '""')}"`
        }
        return value
      }).join(','))
    ].join('\n')

    // 添加BOM以支持Excel正确显示中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `房间数据_${new Date().toLocaleDateString()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    Message.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    Message.error('导出失败，请重试')
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  roomStore.setPagination({ current: page })
  roomStore.fetchRooms()
}

// 处理页面大小变化
const handlePageSizeChange = (pageSize) => {
  roomStore.setPagination({ current: 1, size: pageSize })
  roomStore.fetchRooms()
}

// 处理添加房间
const handleAddRoom = () => {
  modalMode.value = 'add'
  modalTitle.value = '添加房间'
  resetForm()
  modalVisible.value = true
}

// 处理查看房间
const handleViewRoom = (record) => {
  modalMode.value = 'view'
  modalTitle.value = '房间详情'
  fillForm(record)
  modalVisible.value = true
}

// 处理编辑房间
const handleEditRoom = (record) => {
  modalMode.value = 'edit'
  modalTitle.value = '编辑房间'
  currentRoomId.value = record.id
  fillForm(record)
  modalVisible.value = true
}

// 处理删除房间
const handleDeleteRoom = async (id) => {
  await roomStore.deleteRoomData(id)
}

// 处理模态框确认
const handleModalOk = async () => {
  if (modalMode.value === 'view') {
    modalVisible.value = false
    return
  }
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  let success = false
  if (modalMode.value === 'add') {
    success = await roomStore.createRoomData(formData)
  } else if (modalMode.value === 'edit') {
    success = await roomStore.updateRoomData(currentRoomId.value, formData)
  }
  
  if (success) {
    modalVisible.value = false
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
}

// 填充表单
const fillForm = (record) => {
  Object.assign(formData, {
    room_number: record.room_number || '',
    floor: record.floor || 1,
    room_type_id: record.room_type?.id || '',
    room_status_id: record.room_status?.id || '',
    area: record.area || 0,
    max_guests: record.max_guests || 1,
    bed_type: record.bed_type || '',
    description: record.description || ''
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    room_number: '',
    floor: 1,
    room_type_id: '',
    room_status_id: '',
    area: 0,
    max_guests: 1,
    bed_type: '',
    description: ''
  })
  formRef.value?.resetFields()
}

// 组件挂载时获取数据
onMounted(async () => {
  await roomStore.fetchRoomTypes()
  await roomStore.fetchRoomStatuses()
  await roomStore.fetchRooms()
})
</script>

<style scoped lang="scss">
.filter-card {
  margin-bottom: 12px;
  
  :deep(.arco-card-body) {
    padding: 12px 16px;
  }
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 8px;
  }
}

.filter-form {
  flex: 1;
  min-width: 0;
}

.filter-row {
  display: grid;
  grid-template-columns: 240px 240px auto;
  gap: 8px 12px;
  align-items: center;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-template-columns: 240px 240px;
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}

.filter-item {
  display: flex;
  align-items: center;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
    width: 100%;
    display: flex;
    align-items: center;
  }
  
  :deep(.arco-form-item-label-col) {
    width: 70px;
    flex: 0 0 70px;
    padding-right: 6px;
  }
  
  :deep(.arco-form-item-label) {
    font-weight: 500;
    color: #1d2129;
    white-space: nowrap;
    text-align: right;
    width: 100%;
    font-size: 13px;
  }
  
  :deep(.arco-form-item-wrapper-col) {
    flex: 1;
    min-width: 0;
  }
  
  :deep(.arco-input-wrapper),
  :deep(.arco-select-view),
  :deep(.arco-picker) {
    width: 100%;
    max-width: 160px;
    min-width: 160px;
  }
}

.button-group {
  grid-column: 3;
  grid-row: 1;
  display: flex;
  justify-content: flex-end;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-column: 1 / -1;
    grid-row: auto;
    margin-top: 4px;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    width: 100%;
    
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.action-buttons {
  flex-shrink: 0;
  
  @media (max-width: 1024px) {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.table-card {
  margin-bottom: 16px;
}
</style>
